export {}

import screenshotImg from '../servers/file-box';
const Http = require('../servers/http');
const Config = require('../config'); 

async function onMessage(msg: any) {
    const room = msg.room();

    if (room) {
        await onRoomMsg(msg);
    } else {
        await onPersonMsg(msg);
    }
}

async function onRoomMsg(msg: any) {
    const room = msg.room(); // 是否是群消息
    const topic = await room.topic();
    console.log(topic);
    // console.log(`群聊--${msg.from().name()}: ${msg.text()}`);
    for(let i = 0; i < Config.WHITELIST_ROOM.length; i++) {
        if (topic === Config.WHITELIST_ROOM[i]) {
            console.log(`${topic}-- ${msg.from().name()}: ${msg.text()}`);
        }
    }
}

async function onPersonMsg(msg: any) {
    const contact = msg.from(); // 发消息人
    const content = msg.text().trim(); // 消息内容
    const alias = await contact.alias(); // 发消息人备注
    // console.log(JSON.stringify(contact));
    // console.log(`发消息人: ${contact.name()}  消息内容: ${content}`);
    for(let i = 0; i < Config.WHITELIST_USER.length; i++) {
        if (contact.name() === Config.WHITELIST_USER[i]) {
            // msg.say(`测试测试`);
            if (/看图片/.test(content)) {
                const pos = content.indexOf(':');
                const url = content.substr(pos+1);
                await screenshotImg(msg, url);
                return;   
            }
            Http('GET' , Config.TULING_BOT.url, {
                "key": Config.TULING_BOT.key,
                "info": content,
                "userid": contact.name()
            }).then((res: any) => {
                console.log(JSON.parse(res.text));
                msg.say(JSON.parse(res.text).text);
            }, (err: any) => {
                console.log('失败');
                msg.say(`哈?? 听不懂你说什么!!`);
            })
            
        }
    }
}

module.exports = onMessage;
